package com.hj.config.security.filter;

import com.hj.config.security.token.PwdLoginToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author hj
 * @Description 密码登录拦截器处理
 */
public class PwdLoginFilter extends AbstractAuthenticationProcessingFilter {

    private final String pwdMobile;

    private final String pwdPassword;

    private final String pwdVerifyCode;

    public PwdLoginFilter(String defaultFilterProcessesUrl, String pwdMobile, String pwdPassword, String pwdVerifyCode, String httpMethod) {
        super(new AntPathRequestMatcher(defaultFilterProcessesUrl, httpMethod));
        this.pwdMobile = pwdMobile;
        this.pwdPassword = pwdPassword;
        this.pwdVerifyCode = pwdVerifyCode;
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
        String mobile = request.getParameter(pwdMobile);
        String password = request.getParameter(pwdPassword);
        String verifyCode = request.getParameter(pwdVerifyCode);
        PwdLoginToken pwdLoginToken = new PwdLoginToken(mobile.trim(), password, verifyCode);
        pwdLoginToken.setDetails(authenticationDetailsSource.buildDetails(request));
        return this.getAuthenticationManager().authenticate(pwdLoginToken);
    }


}
